<?php
namespace app\shop\controller;
use think\Controller;
use think\request;
use think\Db;
use app\shop\controller\Common;
use app\service\shopService;
use app\service\lifeapiService;
class Shop extends Common{
	//店铺列表
	public function shoplist(){
		
		session('url',request()->url());
		$this->assign("title","商铺列表");
		$this->assign("bottom_type","3");
		$data=Db::table("zz_shop")->order('shop_sort desc')->limit(3)->select();
		$this->assign("data",$data);
		return $this->fetch();
	}
	public function getshopdata(){
		$data=Db::table("zz_shop")->order('shop_sort desc')->select();
		$str="";
		foreach ($data as $key => $value) {
			$url=url('shopgoodlist')."?shop_id=".$value["shop_id"];
			$str=$str."<div class='lie clearfloat' style='border-top:0px solid #000'>";
				$str=$str."<a href='".$url."'>";
					$str=$str."<div class='tu clearfloat fl'>";
						$str=$str."<img src='http://www.jfzhiwen.com/shoplogo/".$value["shop_logo"]."'/>";
					$str=$str."</div>";
				$str=$str."</a>";
				$str=$str."<div class='right clearfloat fl' >";
					$str=$str."<a href='".$url."'>";
						$str=$str."<p class='tit'>&nbsp;&nbsp;".$value["shop_name"]."</p>";
						$str=$str."<p class='tit'>&nbsp;&nbsp;地址:".$value["shop_address"]."</p>";
						$str=$str."<p class='tit'>&nbsp;&nbsp;电话:".$value["shop_phone"]."</p>";
						$str=$str."<p class='tit'>&nbsp;&nbsp;营业时间:".$value["shop_workingtime"]."</p>";
					$str=$str."</a>";
							
				$str=$str."</div>";
			$str=$str."</div>";
		}
		echo $str;
	}

	//商品列表
	public function shopgoodlist(){
		
		session('url',request()->url());
		$this->assign("title","商品列表");
		$this->assign("bottom_type","3");
		$shop_id=request()->get("shop_id");
		if(empty($shop_id)){
			$url=url('shoplist');
			echo "<script>alert('店铺错误');window.location.href='$url'</script>";
			exit;
		}
		$shopinfo=Db::table("zz_shop")->where("shop_id",$shop_id)->find();

		$this->assign("shopinfo",$shopinfo);
		$data=Db::table("zz_goods")->where('shop_id',$shop_id)->where('state','1')->select();
		if(empty($data)){
			return $this->fetch("nouploadgoodmsg");
		}
		$this->assign("data",$data);
		
		$arr=Db::table("zz_shopcart")->where('uid',session('user_id'))->select();
		$shopcart=array();
		$ordermoney=0;
		foreach ($arr as $key => $value) {
			$shopcart[$value["goods_id"]]=$value["num"];
			$ordermoney=$ordermoney+$value["salesprice"]*$value["num"];
		}
		$this->assign("ordermoney",$ordermoney);
		$this->assign("shopcart",$shopcart);
		//查询用户是否添加了收货地址
		$num=Db::table('zz_address')->where('uid',session('user_id'))->count();
		$this->assign("num",$num);
		return $this->fetch();
	}
	//商品列表
	public function goodinfo(){
		session('url',request()->url());
		$this->assign("title","商品详情");
		$this->assign("bottom_type","3");
		$goods_id=request()->get("goods_id");
		if(empty($goods_id)){
			$url=url('shoplist');
			echo "<script>alert('店铺错误');window.location.href='$url'</script>";
			exit;
		}
		$goodinfo=Db::table("zz_goods")->where("goods_id",$goods_id)->find();
		if($goodinfo["state"]!="1"){
			$url=url('shoplist');
			echo "<script>alert('该商品已下架');window.location.href='$url'</script>";
			exit;
		}
		$this->assign("goodinfo",$goodinfo);
		return $this->fetch();
	}
	public function shopcart(){
		session('url',request()->url());
		$shop_id=request()->get("shop_id");
		$address_id=request()->has("address_id")? request("address_id")->get("address_id"):"0";
		//查询购物车的商品
		$cartinfo=Db::table("zz_shopcart")->where("shop_id",$shop_id)->where("uid",session('user_id'))->select();
		$data["ordermoney"]=0;
		$data["num"]=0;
		$data["shop_id"]=$shop_id;
		foreach ($cartinfo as $key => $value) {
			$data["ordermoney"]=$data["ordermoney"]+$value["salesprice"]*$value["num"];
			$data["num"]=$data["num"]+$value["num"];
		}
		if($data["num"]=="0"){
			$url=url('shoplist')."?shop_id=".$shop_id;
			echo "<script>window.location.href='$url'</script>";
			exit;
		}
		if($address_id=="0"){
			//查询用户默认收货地址
			$address=Db::table("zz_address")->where('uid',session('user_id'))->where('default','1')->find();
			if(empty($address)){
				$address=Db::table("zz_address")->where('uid',session('user_id'))->find();
			}
		}else{
			$address=Db::table("zz_address")->where('address_id',$address_id)->find();
		}
		$this->assign("shop_id",$shop_id);
		$this->assign("address",$address);
		$this->assign("title","确认订单");
		$this->assign("bottom_type","3");
		$this->assign("cartinfo",$cartinfo);
		$this->assign("data",$data);
		return $this->fetch();
	}
	public function orderpay(){
		session('url',request()->url());
		if(request()->post()){
			$data=request()->post();
			
			$data["out_order_no"]=date('YmdHis').rand(10000000,99999999);
			$res=(new shopService())->orderAdd(session('user_id'),$data);
			$url=url('orderpay')."?order_id=".$res;
			echo "<script>window.location.href='$url'</script>";
			exit;
			
		}else{
			$order_id=request()->get("order_id");
			$data=Db::table("zz_order_online")->where("order_id",$order_id)->find();

			$this->assign("title","订单支付");
			$this->assign("bottom_type","3");
			
			$this->assign("data",$data);
			return $this->fetch();
		}
	}

	public function createorder(){
		$order_id=request()->param("order_id");

		$data=Db::table("zz_order_online")->where("order_id",$order_id)->find();

		//查询商铺信息
		$shopinfo=Db::table("zz_shop")->where("shop_id",$data["shop_id"])->find();
				
		$token="201907BBd3f00852d32b468db3c4667e7fdf0C73";
		$api = new lifeapiService();
		//$order["out_order_no"]=date('YmdHis').rand(10000000,99999999);
		//查询会员信息
		$userinfo=(new shopService())->userFind(session('user_id'));
		$notifyurl='https://www.jfzhiwen.com/shop/ali/onlinenotice';
		$result = $api->orderCreate(json_encode(['out_trade_no' =>$data["out_order_no"], 'total_amount' =>  $data["order_money"], 'buyer_id' =>  $data["buyer_id"],'subject' => $shopinfo["shop_name"].'消费', 'token' => $token,'notifyurl' => $notifyurl]));
		
		if(property_exists($result,'sub_msg')){
			
			return json(['info' => $result->sub_msg]);
		}else{
			//添加进数据库
			$order["order_id"]=$order_id;
			$order['transaction_id'] =  $result->trade_no;
			$orderAdd = Db::table("zz_order_online")->update($order);
			//返回结果到前台唤起收银台
			if(!empty($data['transaction_id'])){
				return json(['order_no' => $order['transaction_id']]);
			}
			
			if($orderAdd){
				return json(['order_no' => $order['transaction_id']]);
			}else{
				return json(['info' => '订单存储失败']);
			}
		}
	}

	

	public function orderconfirmtest(){
		
		$data=request()->post();
		$goods_id=$data["goods_id"];
		$goods=array();
		$data["num"]=0;
		foreach ($goods_id as $id => $num) {
			if($num!="0"){
				$goodinfo=Db::table("zz_goods")->where("goods_id",$id)->find();
				$goodinfo["num"]=$num;
				$data["num"]=$data["num"]+$num;
				$goods[]=$goodinfo;
			}
		}
		//查询用户默认收货地址
		$address=Db::table("zz_address")->where('uid',session('openid'))->where('default','1')->find();
		if(empty($address)){
			$address=Db::table("zz_address")->where('uid',session('openid'))->find();
		}
		$this->assign("data",$data);
		$this->assign("address",$address);
		$this->assign("goods",$goods);
		$this->assign("title","确认订单");
		$this->assign("bottom_type","3");
		return $this->fetch();
	}
	

	public function cartAdd(){
		$goods_id=request()->param("goods_id");
		$result=Db::table("zz_shopcart")->where('goods_id',$goods_id)->where('uid',session('user_id'))->find();
		if($result){
			$res=Db::table("zz_shopcart")->where("id",$result["id"])->setInc('num', 1);
			echo $res;die;
		}else{
			$goodinfo=Db::table("zz_goods")->where("goods_id",$goods_id)->find();
			$shopcart["goods_id"]=$goods_id;
			$shopcart["goods_name"]=$goodinfo["goods_name"];
			$shopcart["price"]=$goodinfo["price"];
			$shopcart["salesprice"]=$goodinfo["salesprice"];
			$shopcart["goods_picture"]=$goodinfo["picture"];
			$shopcart["shop_id"]=$goodinfo["shop_id"];
			$shopcart["num"]=1;
			$shopcart["uid"]=session('user_id');
			$res=Db::table("zz_shopcart")->insert($shopcart);
			echo $res;die;
		}
	}
	public function cartDec(){
		$goods_id=request()->param("goods_id");
		$result=Db::table("zz_shopcart")->where('goods_id',$goods_id)->where('uid',session('user_id'))->find();
		if($result["num"]>1){
			$res=Db::table("zz_shopcart")->where("id",$result["id"])->setDec('num', 1);
			echo $res;die;
		}else{
			$res=Db::table("zz_shopcart")->where('id',$result["id"])->delete();
			echo "0";die;
		}
	}
	public function cartMoney(){
		$shop_id=request()->param('shop_id');
		$shopcart=Db::table("zz_shopcart")->where('shop_id',$shop_id)->where('uid',session('user_id'))->select();
		$ordermoney=0;
		foreach ($shopcart as $key => $value) {
			$ordermoney=$ordermoney+$value["salesprice"]*$value["num"];
		}
		echo $ordermoney;
	}





	//产生随机字符串，不长于32位
    public function createNoncestr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }

    //生成签名
    protected function MakeSign($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    //生成签名
    protected function MakeSigns($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $result = md5($string);
        return $result;
    }

    //输出xml字符
    public function ToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key => $val){
            if (is_numeric($val)){
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }else{
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

     //格式化参数格式化成url参数
    public function ToUrlParams($value){
        $buff = "";
        foreach($value as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    //将对象转换成数组
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach($_arr as $key=>$val){
            if($key !== 'gioouts'){
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
                $arr[$key] = $val;
            }
        }
        return $arr;
    }
}